#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "sikle.h"

StringPool* StringPool_new(unsigned int size)
{
  StringPool* sp = (StringPool*)malloc(sizeof(StringPool));

  sp->size = size;
  sp->base = (char*)malloc(size);
  sp->end = 0;

  return sp;
}

void StringPool_delete(StringPool* sp)
{
  if(sp) {
    if(sp->base)
      free(sp->base);
    free(sp);
  }
}

SPString SPString_new(StringPool* pool, char* data, int size)
{
  SPString sps;

  sps.size = size;
  sps.offset = pool->end;
  strncpy(pool->base + pool->end, data, size);
  pool->end += size;

  if(pool->end > pool->size) {
    printf("ERROR: SPString Memory SUCK!");
    exit(0);
  }

  return sps;
}

SPString SPString_concat(StringPool* pool, SPString sps0, SPString sps1)
{
  SPString sps;
  char* base;

  sps.size = sps0.size + sps1.size;
  sps.offset = pool->end;
  base = pool->base;

  strncpy(base + pool->end, base + sps0.offset, sps0.size);
  strncpy(base + pool->end + sps0.size, base + sps1.offset, sps1.size);
  pool->end += sps.size;

  if(pool->end > pool->size) {
    printf("ERROR: SPString Memory SUCK!");
    exit(0);
  }

  return sps;
}

void StringPool_dump(StringPool* sp)
{
  sp->base[sp->end] = 0;
  
  printf("StringPoolBase: %p\n%s\n", sp->base, sp->base);
}
